import React, { useState, useEffect } from 'react';
import { Table, Button, Space, Tag, Modal, Input, message } from 'antd';
import { PlayCircleOutlined, PauseCircleOutlined, DeleteOutlined, EyeOutlined } from '@ant-design/icons';
import axios from 'axios';
import ContainerLogs from '../components/ContainerLogs';

const Containers = () => {
  const [containers, setContainers] = useState([]);
  const [loading, setLoading] = useState(false);
  const [logModalVisible, setLogModalVisible] = useState(false);
  const [selectedContainer, setSelectedContainer] = useState(null);
  const [searchText, setSearchText] = useState('');

  useEffect(() => {
    fetchContainers();
    const interval = setInterval(fetchContainers, 3000);
    return () => clearInterval(interval);
  }, []);

  const fetchContainers = async () => {
    try {
      const response = await axios.get('/api/containers');
      setContainers(response.data);
    } catch (error) {
      message.error('获取容器列表失败');
    }
  };

  const handleStart = async (containerId) => {
    try {
      await axios.post(`/api/containers/${containerId}/start`);
      message.success('容器已启动');
      fetchContainers();
    } catch (error) {
      message.error('启动容器失败');
    }
  };

  const handleStop = async (containerId) => {
    try {
      await axios.post(`/api/containers/${containerId}/stop`);
      message.success('容器已停止');
      fetchContainers();
    } catch (error) {
      message.error('停止容器失败');
    }
  };

  const handleDelete = async (containerId) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个容器吗？此操作不可恢复。',
      onOk: async () => {
        try {
          await axios.delete(`/api/containers/${containerId}`);
          message.success('容器已删除');
          fetchContainers();
        } catch (error) {
          message.error('删除容器失败');
        }
      }
    });
  };

  const showLogs = (container) => {
    setSelectedContainer(container);
    setLogModalVisible(true);
  };

  const filteredContainers = containers.filter(container => 
    container.Names.some(name => name.toLowerCase().includes(searchText.toLowerCase())) ||
    container.Image.toLowerCase().includes(searchText.toLowerCase())
  );

  const columns = [
    {
      title: '容器名称',
      dataIndex: 'Names',
      key: 'name',
      render: (names) => names[0]?.replace('/', '') || '-',
    },
    {
      title: '镜像',
      dataIndex: 'Image',
      key: 'image',
    },
    {
      title: '状态',
      dataIndex: 'State',
      key: 'state',
      render: (state) => (
        <Tag color={state === 'running' ? 'green' : 'red'}>
          {state}
        </Tag>
      ),
    },
    {
      title: '端口',
      dataIndex: 'Ports',
      key: 'ports',
      render: (ports) => ports.map(p => `${p.PrivatePort}:${p.PublicPort}`).join(', ') || '-',
    },
    {
      title: '创建时间',
      dataIndex: 'Created',
      key: 'created',
      render: (created) => new Date(created * 1000).toLocaleString(),
    },
    {
      title: '操作',
      key: 'actions',
      render: (_, record) => (
        <Space>
          {record.State !== 'running' ? (
            <Button
              type="primary"
              icon={<PlayCircleOutlined />}
              size="small"
              onClick={() => handleStart(record.Id)}
            >
              启动
            </Button>
          ) : (
            <Button
              icon={<PauseCircleOutlined />}
              size="small"
              onClick={() => handleStop(record.Id)}
            >
              停止
            </Button>
          )}
          <Button
            icon={<EyeOutlined />}
            size="small"
            onClick={() => showLogs(record)}
          >
            日志
          </Button>
          <Button
            danger
            icon={<DeleteOutlined />}
            size="small"
            onClick={() => handleDelete(record.Id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <h1>容器管理</h1>
      <div style={{ marginBottom: 16 }}>
        <Input.Search
          placeholder="搜索容器名称或镜像"
          value={searchText}
          onChange={(e) => setSearchText(e.target.value)}
          style={{ width: 300 }}
        />
      </div>
      <Table
        columns={columns}
        dataSource={filteredContainers}
        rowKey="Id"
        loading={loading}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 个容器`,
        }}
      />
      <Modal
        title={`容器日志 - ${selectedContainer?.Names?.[0]?.replace('/', '')}`}
        open={logModalVisible}
        onCancel={() => setLogModalVisible(false)}
        width={800}
        footer={null}
      >
        <ContainerLogs containerId={selectedContainer?.Id} />
      </Modal>
    </div>
  );
};

export default Containers;
